package com.soulkun.smarthome.ui.main.home

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.PersistableBundle
import android.view.KeyEvent
import android.view.View
import androidx.activity.viewModels
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.journeyapps.barcodescanner.DecoratedBarcodeView
import com.soulkun.smarthome.R
import com.soulkun.smarthome.databinding.AppActivityMainHomeAddDeviceBinding
import com.soulkun.smarthome.logic.Constant
import com.soulkun.smarthome.logic.dto.DeviceQRCodeDTO
import com.soulkun.smarthome.logic.dto.UserMessageDTO
import com.soulkun.smarthome.logic.enum.MessageCodeEnum
import com.soulkun.smarthome.logic.manager.BroadcastManager
import com.soulkun.smarthome.ui.main.AppMainUserMessageDialog
import com.soulkun.smarthome.ui.main.home.dialog.AppMainHomeAddDeviceNameDialog
import com.soulkun.smarthome.ui.main.home.manager.SoulkunCaptureManager
import com.soulkun.smarthome.ui.main.home.viewmodel.AppMainHomeAddDeviceViewModel
import soulkun.library.mvvm.component.BaseDataBindingActivity
import soulkun.library.utils.screen.ScreenUtils
import soulkun.library.utils.toast
import soulkun.library.utils.visible

class AppMainHomeAddDeviceActivity :
    BaseDataBindingActivity<AppActivityMainHomeAddDeviceBinding>() {

    private val viewModel by viewModels<AppMainHomeAddDeviceViewModel> { defaultViewModelProviderFactory }

    private val captureManager by lazy {
        SoulkunCaptureManager(this, requireDataBinding().dbvMainHomeAddDeviceCamera)
    }

    private val deviceNameDialog by lazy {
        AppMainHomeAddDeviceNameDialog(this, viewModel) {
            resumeDecode()
        }
    }

    private val userBroadcastReceiver by lazy {
        BroadcastManager.SoulkunBroadcastReceiver(MessageCodeEnum.User) {
            val userMessageDTO = it as UserMessageDTO
            val userMessageDialog = AppMainUserMessageDialog(userMessageDTO.message)
            userMessageDialog.show(supportFragmentManager, "userMessageDialog")
        }
    }

    override fun setLayout(): Int {
        return R.layout.app_activity_main_home_add_device
    }

    override fun initIntent(savedInstanceState: Bundle?) {
        viewModel.roomLiveData.value = intent.getParcelableExtra(Constant.BUNDLE_ROOM)
        captureManager.initializeFromIntent(intent, savedInstanceState)
    }

    override fun initView() {
        ScreenUtils.setTranslucentStatusBar(this)
        ScreenUtils.setWhiteStatusText(this)
        if (!hasFlashLight()) {
            requireDataBinding().ibMainHomeAddDeviceIconFlashlight.visible(false)
        }
    }

    override fun initData() {
        captureManager.decode()
        requireDataBinding().onClickListener = View.OnClickListener {
            when (it.id) {
                R.id.ib_main_home_add_device_icon_flashlight -> {
                    if (viewModel.flashLightOnLiveData.value!!) {
                        requireDataBinding().dbvMainHomeAddDeviceCamera.setTorchOff()
                    } else {
                        requireDataBinding().dbvMainHomeAddDeviceCamera.setTorchOn()
                    }
                }
                R.id.iv_main_home_add_device_icon_close -> {
                    finish()
                }
            }
        }
    }

    override fun initListener() {
        captureManager.setOnReturnResultListener {
            if (viewModel.roomLiveData.value != null) {
                try {
                    val gson = Gson()
                    val deviceQRCodeDTO = gson.fromJson(it, DeviceQRCodeDTO::class.java)
                    viewModel.deviceQRCodeLiveData.value = deviceQRCodeDTO
                    deviceNameDialog.show(supportFragmentManager, "DeviceNameDialog")
                } catch (jsonSyntaxException: JsonSyntaxException) {
                    jsonSyntaxException.printStackTrace()
                    "无法解析非官方设备二维码，添加设备失败".toast()
                    resumeDecode()
                }
            } else {
                "当前房间信息异常，请退出页面重新进入".toast()
                resumeDecode()
            }
        }
        requireDataBinding().dbvMainHomeAddDeviceCamera.setTorchListener(object :
            DecoratedBarcodeView.TorchListener {
            override fun onTorchOff() {
                viewModel.flashLightOnLiveData.value = false
                requireDataBinding().ibMainHomeAddDeviceIconFlashlight.setImageResource(R.drawable.app_main_home_add_device_icon_flashlight_on)
            }

            override fun onTorchOn() {
                viewModel.flashLightOnLiveData.value = true
                requireDataBinding().ibMainHomeAddDeviceIconFlashlight.setImageResource(R.drawable.app_main_home_add_device_icon_flashlight_off)
            }
        })
    }

    override fun onStart() {
        super.onStart()
        BroadcastManager.registerBroadcast(mContext, MessageCodeEnum.User, userBroadcastReceiver)
    }

    override fun onResume() {
        super.onResume()
        captureManager.onResume()
    }

    override fun onPause() {
        super.onPause()
        captureManager.onPause()
    }

    override fun onStop() {
        super.onStop()
        BroadcastManager.unregisterBroadcast(mContext, userBroadcastReceiver)
    }

    override fun onDestroy() {
        super.onDestroy()
        captureManager.onDestroy()
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        captureManager.onSaveInstanceState(outState)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return requireDataBinding().dbvMainHomeAddDeviceCamera.onKeyDown(
            keyCode,
            event
        ) || super.onKeyDown(keyCode, event)
    }

    //判断是否有闪光灯功能
    private fun hasFlashLight() =
        applicationContext.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)

    private fun resumeDecode() {
        requireDataBinding().dbvMainHomeAddDeviceCamera.resume()
        captureManager.decode()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

}